package com.ciwong.epaper.modules.cordva.html;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.ui.BaseFragment;
import com.ciwong.epaper.ui.MainActivity;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.widget.TitleBar;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaInterfaceImpl;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.engine.SystemWebChromeClient;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;

import java.util.concurrent.ArrayBlockingQueue;

/**
 */
public abstract class BaseHtmlFragment extends BaseFragment implements SystemWebViewClient.LoadCallback, GoBackListener {
    public static final String TAG = "BaseHtmlFragment";

    protected CordovaWebView cordovaWebView;
    public final ArrayBlockingQueue<String> onPageFinishedUrl = new ArrayBlockingQueue<String>(5);
    protected StringBuffer  startURL;
    //用于加载的webView
    public    SystemWebView webView;

    //无网时提示信息
    protected ViewGroup no_net_work;
    protected Button try_again;

    private String currentTitle;

    protected CordovaInterfaceImpl cordovaInterface ;
    protected SystemWebViewEngine  systemWebViewEngine;

    public TitleBar getTitleBar() {
        return mTitleBar;
    }

    private TitleBar mTitleBar;
    /**
     * 返回按钮事件
     */
    private GoBackListener mGoBackListener;
    protected void setGoBackListener(GoBackListener listener) {
        mGoBackListener = listener;
    }
    public CordovaWebView getCordovaWebView() {
        return cordovaWebView;
    }

    //发送回调
    protected void sendCallBack(String callbackId, String msg) {
        //        if (!callbackId.isEmpty()  )
        if (!TextUtils.isEmpty(callbackId) && !TextUtils.isEmpty(msg)) {
            CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
            callbackContext.success(msg);
        }
    }

    //发送回调
    protected void sendCallBackInt(String callbackId, int msg) {
        if (!callbackId.isEmpty()) {
            CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
            callbackContext.success(msg);
        }
    }


    public void setStartURL(String url) {
        String handleUrl = handleURL(url);
        this.startURL = new StringBuffer(handleUrl);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.htmlfragment, container,
                false);
        findViews(view);
        initEvent();
        init();
        return view;
    }



    protected void loadUrl(String url) {
        String handleUrl = handleURL(url);
        if (TextUtils.isEmpty(handleUrl))
            handleUrl = startURL.toString();
        if (TextUtils.isEmpty(handleUrl)) {
            toastInCenter("错误：路径不存在!");
            return;
        }
        CWLog.i(" loadUrl:", startURL.toString());
        webView.loadUrl(handleUrl);
    }

    private String handleURL(String url) {
        if (!TextUtils.isEmpty(url))
            if (!url.contains("http") && !url.contains("file://"))//解决连接中不包含http 导致闪退的bug
                url = "http://" + url;
        return url;
    }


    protected void findViews(View view) {

        try {
            webView = (SystemWebView) view.findViewById(R.id.cordovaWebView);
            webView.getSettings().setSavePassword(false);
            webView.getSettings().setBuiltInZoomControls(false);
            webView.getSettings().setDomStorageEnabled(true);
            webView.getSettings().setTextZoom(EApplication.getInstance().gettextZoom());
            if (Build.VERSION.SDK_INT >= 21) {//解决webview白板问题
                webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            no_net_work = (ViewGroup) view.findViewById(R.id.ll_no_net);
            try_again = (Button) view.findViewById(R.id.btn_retry);
            mTitleBar =  (TitleBar)view.findViewById(R.id.activity_base_titlebar);
            mTitleBar.setBackListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    if(mGoBackListener!=null){
                        mGoBackListener.goBack();
                    }
                }
            });
//            webView.goBack();
        } catch (RuntimeException e) {
            e.printStackTrace();
        }

    }


    protected void initEvent() {

    }

    protected void init() {
        try {
            //初始化cordovaWebView
            systemWebViewEngine = new SystemWebViewEngine(webView);

            cordovaWebView = new CordovaWebViewImpl(systemWebViewEngine);
            cordovaWebView.clearCache();
            //Set up the webview
            ConfigXmlParser parser = new ConfigXmlParser();
            parser.parse(mActivity);
            cordovaInterface = new CordovaInterfaceImpl(mActivity) {
                @Override
                public Object onMessage(String id, Object data) {
                    //影响在线加载，屏蔽掉
                    if ("onPageFinished".equals(id)) {
                        try {
                            onPageFinishedUrl.add((String) data);

                        } catch (IllegalStateException e) {

                        }
                    }
                    return super.onMessage(id, data);
                }
            };
            cordovaWebView.init(this, cordovaInterface, parser.getPluginEntries(), parser.getPreferences());

            SystemWebViewClient systemWebViewClient = new SystemWebViewClient(systemWebViewEngine) {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }

                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    super.onReceivedError(view, errorCode, description, failingUrl);
                    webViewError();
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    if (webView.canGoBack()){
                        setBackImg(R.mipmap.nav_btn_return_left);
                    }

                }
            };
            SystemWebChromeClient systemWebChromeClient = new SystemWebChromeClient(systemWebViewEngine) {
                @Override
                public void onReceivedTitle(WebView view, String title) {//监听标题改变
                    if (NetworkUtils.isOnline() && !TextUtils.isEmpty(title)) {
                        currentTitle = title;
                        setTitleText(title);
                        //                    System.out.println("网页的标题title为 ："+title);
                        if (!webpageException(title)) {
                            webViewError();
                        } else {
                            webView.setVisibility(View.VISIBLE);
                            no_net_work.setVisibility(View.GONE);
                        }
                    }
                }
            };
            webView.setWebViewClient(systemWebViewClient);
            webView.setWebChromeClient(systemWebChromeClient);

            try_again.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (NetworkUtils.isOnline()) {
                        if (!webpageException(currentTitle)) {
                            webView.setVisibility(View.GONE);
                        } else {
                            webView.setVisibility(View.VISIBLE);
                        }
                        //重新加载网页
                        webView.loadUrl(startURL.toString());
                        no_net_work.setVisibility(View.GONE);
                    }
                }
            });
        } catch (Exception e) {

        }

    }

    /**
     * 通过标题判断网页是否异常
     *
     * @param title 标题
     * @return true 表示网页正常情况，false表示网页异常
     */
    private boolean webpageException(String title) {
        if (title == null) return true;
        if (title.contains("网页")) {
            if (title.contains("找不到") || title.contains("无法打开")
                    || title.contains("错误") || title.contains("异常"))
                return false;
        }
        return true;
    }

    private void webViewError() {
        if (webView != null && no_net_work != null) {
            webView.setVisibility(View.GONE);
            no_net_work.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDestroy() {
        if (webView != null) {
            webView.destroy();
            webView.setVisibility(View.GONE);
        }
        if (cordovaWebView != null) {
            cordovaWebView.getEngine().destroy();
            cordovaWebView.getPluginManager().onDestroy();
            cordovaWebView = null;
        }
        super.onDestroy();
    }



    protected void loadData() {
        showNetErrorWork(getResources().getString(R.string.get_errorresing_info));
    }

    @Override
    public void onLoadOver() {

    }

    @Override
    public void onBackFinish() {
        System.out.println("返回键点击了");

    }

    /**
     * 无网络环境下的时候，显示提醒页面
     */
    protected void showNetErrorWork(String noNetTip) {
        if (!NetworkUtils.isOnline()) {
            if (webView != null)
                webView.setVisibility(View.GONE);
            if (no_net_work != null)
                no_net_work.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void goBack() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();
        } else {
//            finish();
        }
    }
    private void finish() {
        if(mActivity!=null&& !(mActivity instanceof MainActivity)){
            mActivity.finish();
        }
    }

    public void setBackImg(int id) {
        if (mTitleBar != null) {
            mTitleBar.showBackBar();
            mTitleBar.setBackImg(id);
        }
    }
    public void hideBackBar() {
        if (mTitleBar != null) {
            mTitleBar.hideBackBar();
        }
    }
    public void setImgRightBtn(int resId) {
        if (mTitleBar != null) {
            mTitleBar.setRightBtnBG(resId);
        }
    }
    public void setTitleText(int resid) {
        if(mTitleBar!=null){
            mTitleBar.setTitle(resid);
        }
    }
    public void setTitleText(String title) {
        if(mTitleBar!=null){
            mTitleBar.setTitle(title);
        }

    }

    public String getTitleText() {
        return mTitleBar!=null? mTitleBar.getTitle():"";
    }
}
